package framework.system.controller;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import framework.core.controller.BaseAction;
import framework.core.util.Kit;
import framework.core.util.ListRange;
import framework.system.entity.SysResource;
import framework.system.entity.SysRole;
import framework.system.entity.front.Role;
import framework.system.service.IMenuService;
import framework.system.service.IRoleService;

/**
 * @ClassName: RoleController 
 * @Description: 角色Controller
 * @author: Ching Wang
 * @date 2013-5-18 下午2:36:18 
 *
 */
@Controller
@RequestMapping("/rolectrl")
public class RoleController extends BaseAction {

	@Resource private IRoleService roleService;
	@Resource private IMenuService menuService;

	/**
	 * @Title: listAll 
	 * @Description: 加载所有角色
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/listAll")
	public void listAll(HttpServletRequest request, HttpServletResponse response) throws Exception{
		List<SysRole> sysRoles = roleService.findAll();
		List<JSONObject> objects = new ArrayList<JSONObject>();
		if(sysRoles != null && sysRoles.size() > 0){
			for(SysRole sysRole : sysRoles){
				JSONObject object = new JSONObject();
				object.put("id", sysRole.getId());
				object.put("name", sysRole.getName());
				objects.add(object);
			}
		}
		outJsonArray(response, objects, "yyyy-MM-dd");
	}  
	
	/**
	 * @Title: listRole 
	 * @Description: 分页查找角色 
	 * @param roleName 角色名称
	 * @param page 第page页
	 * @param rows 获取rows条记录
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/listRole")
	public void listRole(String roleName, String page, String rows, HttpServletRequest request, HttpServletResponse response) throws Exception{
		ListRange<Role> range = new ListRange<Role>();
		List<Role> roles = new ArrayList<Role>();
		Role role = null;
		Set<SysResource> sysResources = null;
		
		DetachedCriteria criteria = DetachedCriteria.forClass(SysRole.class);
		if(Kit.isNotNull(roleName)){
			criteria.add(Restrictions.like("name", roleName, MatchMode.ANYWHERE));
		}
		long total = roleService.getCount(criteria);
		if(total > 0){
			List<SysRole> sysRoles =  roleService.listRole(criteria, page, rows);
			for(SysRole sysRole : sysRoles){
				role = new Role();
				 BeanUtils.copyProperties(sysRole, role);
				 sysResources = sysRole.getSysResources();
				 if(sysResources != null && sysResources.size() > 0){
					 List<String> resourceIds = new ArrayList<String>();
					 List<String> resourceNames = new ArrayList<String>();
					 for(SysResource sysResource : sysResources){
						 resourceIds.add(sysResource.getId());
						 resourceNames.add(sysResource.getText());
					 }
					 role.setResourceIds(resourceIds);
					 role.setResourceNames(resourceNames);
				 }
				 roles.add(role);
			}
		}
		range.setRows(roles);
		range.setTotal(total);
		outJson(response, range, "yyyy-MM-dd");
	}
	
	/**
	 * @Title: editRole 
	 * @Description: 编辑角色
	 * @param role 角色属性集合
	 * @param oper 操作类型（add：添加,edit：编辑）
	 * @param session
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/editRole")
	public void editRole(Role role, String oper, HttpSession session, HttpServletRequest request, HttpServletResponse response) throws Exception{
		SysRole sysRole = new SysRole();
		if(Kit.isNotNull(role.getId())){
			sysRole = roleService.getRole(role.getId());
		}
		if(role.getResourceIds() != null && role.getResourceIds().size() > 0){
			Set<SysResource> sysResources = new HashSet<SysResource>();
			for(String str : role.getResourceIds()){
				SysResource sysResource = menuService.getResource(str);
				sysResources.add(sysResource);
			}
			sysRole.setSysResources(sysResources);
		}
		sysRole.setName(role.getName());
		sysRole.setRemark(role.getRemark());
		roleService.saveOrUpdate(sysRole);
		JSONObject obj = new JSONObject();
		obj.put("success", true);
		if(Kit.isNotNull(oper) && "add".equals(oper)){
			obj.put("message", "添加角色信息成功。");
		}
		if(Kit.isNotNull(oper) && "edit".equals(oper)){
			obj.put("message", "更新角色信息成功。");
		}
		outJson(response, obj, "yyyy-MM-dd");
	}
	
	/**
	 * @Title: delRole 
	 * @Description: 删除角色信息
	 * @param roleIds 角色ID集合
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/delRole")
	public void delRole(String roleIds, HttpServletRequest request, HttpServletResponse response) throws Exception{
		ListRange<Role> range = new ListRange<Role>();
		if(Kit.isNotNull(roleIds)){
			range = roleService.delRole(roleIds.split(","));
			if(range.isSuccess()){
				range.setMessage("删除角色信息成功.");
			}
		}
		else{
			range.setMessage("未找到相关角色，请确认.");
			range.setSuccess(false);
		}
		outJson(response, range, "yyyy-MM-dd");
	}
}
